package com.student.xujiang.mysmalluse.retrofit2andrxjava2;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.jackson.JacksonConverterFactory;

/**
 * Created by xujiang on 2017/3/21.
 */

public class RetroFactory {
    //待换
    private static String baseUrl = "http://192.168.0.107:8082/MyWeb/";

    private static OkHttpClient httpClient =  new OkHttpClient.Builder()
            .addInterceptor(new Interceptor() {  //添加一个拦截器
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request.Builder builder = chain.request().newBuilder();
                    builder.addHeader("token","abc");
                    return chain.proceed(builder.build());
                }
            })
            .connectTimeout(30, TimeUnit.SECONDS) //其中connectTimeout是连接超时时间，在指定时间内还没有连接到服务器就会报SocketTimeout异常，
            .readTimeout(30,TimeUnit.SECONDS)  //而readTimeout是读取超时时间，是连接后在指定时间还没有获取到数据就超时。
            .build();

    private static RetrofitService retrofitService = new Retrofit.Builder()
            .baseUrl(baseUrl)
            .addConverterFactory(JacksonConverterFactory.create()) //addConverterFactory是指定使用Jackson来解析Json数据,转换器
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) //而addCallAdapterFactory，通过这个转换，才能将服务器的返回值从Retrofit默认的Call变为Observable
            .client(httpClient)
            .build()
            .create(RetrofitService.class);

    public static RetrofitService getInstance(){
        return retrofitService;
    }

}
